using Engine;

namespace RuthlessConquest {
    public class ExplosionParticleSystem : ParticleSystem<ExplosionParticleSystem.Particle> {
        public class Particle : global::RuthlessConquest.Particle {
            public Vector2 Velocity;

            public float TimeToLive;

            public Color BaseColor;
        }

        public Random Random = new();

        public ExplosionParticleSystem(Vector2 position, Vector2 velocity, float density, float size, Color color) : base((int)(30f * density), 1) {
            Texture = Textures.Explosion;
            TextureSlotsCount = 1;
            for (int i = 0; i < Particles.Length; i++) {
                Particle obj = Particles[i];
                obj.IsActive = true;
                float num = Random.Float(0.2f, 1f);
                Vector2 vector = Random.Vector2(num);
                obj.Position = position + 100f * vector * size;
                obj.BaseColor = color;
                obj.Size = new Vector2(MathUtils.Lerp(30f, 24f, num));
                obj.TimeToLive = MathUtils.Lerp(2f, 1f, num) * Random.Float(0.4f, 1f);
                obj.Velocity = size * 1500f * vector * Random.Float(0.5f, 1.2f) + velocity;
                obj.UseAdditiveBlending = true;
            }
        }

        public override bool Run(float dt) {
            dt = MathUtils.Clamp(dt, 0f, 0.1f);
            float num = MathUtils.Pow(0.02f, dt);
            bool flag = false;
            for (int i = 0; i < Particles.Length; i++) {
                Particle particle = Particles[i];
                if (particle.IsActive) {
                    flag = true;
                    particle.TimeToLive -= dt;
                    if (particle.TimeToLive > 0f) {
                        particle.Position += particle.Velocity * dt;
                        particle.Velocity *= num;
                        particle.Color = particle.BaseColor * MathUtils.Saturate(0.8f * particle.TimeToLive);
                    }
                    else {
                        particle.IsActive = false;
                    }
                }
            }
            return !flag;
        }
    }
}